/**
 * 
 */
package cn.biplam.common.runtime;

import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;


/**
 * 运行任务池
 * @author 	WangSong 2009-6-26 下午05:21:27
 * @version 1.0
 */
public abstract class Task {

	public static final String Group_Name="biplam";

	/**线程组*/
	private static ThreadGroup group=null;
	private static KvMap<String, TaskBase> threads=null;

	/**
	 * 返回运行任务组(所有纳入任务管理的线程创建到该任务组)
	 * @return
	 */
	public static ThreadGroup get(){
		if(group==null){
			group=new ThreadGroup(Task.Group_Name);
		}
		return group;
	}

	/**
	 * 从任务组中返回指定的任务
	 * @param sTaskName
	 * @return
	 * @throws ErrorMessage
	 */
	public static TaskBase getTask(String sTaskName) throws ErrorMessage{
		TaskBase task=null;
		try{
			if(group!=null){
				Thread[] list =new Thread[group.activeCount()];
				group.enumerate(list);
				for(Thread ite:list){
					if(sTaskName.equals(ite.getName())){
						task = threads.getByKey(ite.getName());
						break;
					}
				}
			}
		}catch(Exception e){
			throw new ErrorMessage(e);
		}
		return task;
	}

	/**
	 * 从线程池中返回指定的现场
	 * @param sTaskName
	 * @return
	 * @throws ErrorMessage
	 */
	public static Thread getThread(String sTaskName) throws ErrorMessage{
		try{
			Thread[] list =new Thread[group.activeCount()];
			group.enumerate(list);
			for(Thread ite:list){
				if(sTaskName.equals(ite.getName())){
					return ite;
				}
			}
		}catch(Exception e){
			throw new ErrorMessage(e);
		}
		return null;
	}

	/**
	 * 将任务放入任务池，并执行
	 * @param task
	 * @throws ErrorMessage
	 */
	public static void putTask(TaskBase task) throws ErrorMessage{
		if(Task.threads==null){
			threads=new KvMap<String, TaskBase>();
		}
		TaskBase cur=(TaskBase) threads.getByKey(task.getName());
		if(cur!=null){
			throw new ErrorMessage("Task("+task.getName()+") has existed!");
		}
		Task.threads.put(task.getName(),task);
		new Thread(Task.get(),task,task.getName()).start();
	}

	/**
	 * 从任务池中移除任务
	 * @param sName
	 * @throws ErrorMessage 
	 */
	public static void popTask(String sTaskName) throws ErrorMessage{
		TaskBase task=Task.getTask(sTaskName);
		if(task!=null){
			Task.threads.removeByKey(task.getName());
		}
	}

	/**
	 * 停止一个任务(需等到该任务单次循环处理结束)
	 * @param sTaskName
	 * @throws ErrorMessage
	 */
	public static void stopTask(String sTaskName) throws ErrorMessage{
		Thread t = Task.getThread(sTaskName);
		if(t==null){
			throw new ErrorMessage("Thread("+sTaskName+") not found!");
		}else{
			if(!t.isInterrupted()){
				t.interrupt();
			}else{
				throw new ErrorMessage("Thread("+sTaskName+") has interrupted!"); 
			}
		}
	}
}
